package org.deri.odhd.buses.index;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.deri.odhd.buses.model.Company;
import org.deri.odhd.buses.model.Journey;
import org.deri.odhd.buses.model.Stop;

import com.csvreader.CsvReader;

public class FileImporter {

	public static Set<Journey> importfiles(InputStream in) throws IOException, ParseException {
		CsvReader reader = new CsvReader(new BufferedReader(new InputStreamReader(in)));
		reader.readHeaders();
		Set<Journey> journeySet = new HashSet<Journey>();
		Map<String, Company> companiesMap = new HashMap<String, Company>();
		int id = 1;
		while (reader.readRecord()) {
			String companyName = reader.get("company name");
			Company company;
			if(companiesMap.containsKey(companyName)){
				company = companiesMap.get(companyName);
			}else{
				company = new Company(companyName,null);
				companiesMap.put(companyName, company);
			}
			String galway = reader.get("Galway");
			Date galwayTime = parseTime(galway);
			Stop galwayStop = new Stop("Galway", galwayTime);
			
			String dublinCity = reader.get("Dublin City");
			Date dublinTime = parseTime(dublinCity);
			Stop dublinStop = new Stop("Dublin City", dublinTime);
			
			String dublinAirport = reader.get("Dublin Airport");
			Date dublinAirportTime = parseTime(dublinAirport);
			Stop dublinAirportStop = new Stop("Dublin Airport", dublinAirportTime);
			
			String day = reader.get("day");
			//TODO journey should have two types: express and multistop
			String type = reader.get("type");
			//TODO consider notes columns
			List<Stop> stops = new ArrayList<Stop>();
			if(galwayStop!=null){
				stops.add(galwayStop);
			}
			if(dublinStop!=null){
				stops.add(dublinStop);
			}
			if(dublinAirportStop!=null){
				stops.add(dublinAirportStop);
			}
			
			//TODO sort the array list based on time
			
			Journey journey = new Journey(String.valueOf(id), day, company, stops);
			journeySet.add(journey);
			id+=1;
		}
		
		return journeySet;
	}
	
	private static SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
	private static Date parseTime(String time) throws ParseException{
		if(time.isEmpty()){
			return null;
		}
		return formatter.parse(time);
	}
}
